package com.lge.clock;
//git diff test
import java.util.List;

import com.lge.clock.alarmclock.Alarms;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.CommonUtil.OPERATOR;
import com.lge.clock.worldclock.LowOnSpaceDialog;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.LGSensor;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.provider.Settings;

public class AlarmClockActivity extends Activity{
	/** Called when the activity is first created. */
	public static final boolean LOG = true;
	/**
	 * Field ALARM.
	 */
	public static final String ALARM = "tab_alarm";
	/**
	 * Field TIMER.
	 */
	public static final String TIMER = "tab_timer";
	/**
	 * Field WORLDCLOCK.
	 */
	public static final String WORLDCLOCK = "tab_worldclock";
	/**
	 * Field STOPWATCH.
	 */
	public static final String STOPWATCH = "tab_stopwatch";
	private static final String TAG = "AlarmClock";

	/**
	 * Field LASTTABID.
	 * (value is ""TapPreferences"")
	 */
	public static final String LASTTABID = "TapPreferences";
	public static int mDeleteSelected;
	public static boolean mSensor = true;
	
	public static boolean mShutDown = false;

	private boolean isLowOnSpace = false;//[hyunjung78.park][1406] 2011.10.12

	// [suhaeng.lee][1456] 2011.10.19 START
	public static int mSelectedID = 0;
	public static boolean mDeleteAll = false;
	// [suhaeng.lee][1456] 2011.10.19 END
	
	private ActionBar actionBar;
	
	private Intent intent;
	
	private static final int ALARM_ID = 0;
	private static final int TIMER_ID = 1;
	private static final int WORLDCLOCK_ID = 2;
	private static final int STOPWATCH_ID = 3;
	
	private int mCurrentTab = ALARM_ID;
	
	//sunghun.an@lge.com Common : Gesture Guide Pop up  [START]
	private boolean mGestureGuide = false;
	private AlertDialog gestureGuideDlg =null;
	private AnimationDrawable mAnimation;
	private CheckBox check = null;
	private SharedPreferences pref;
	//sunghun.an@lge.com Common : Gesture Guide Pop up  [END]	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		isLowOnSpace = CommonUtil.isLowOnSpaceMemory(this);
		if(isLowOnSpace) {			
			Intent mIntent = new Intent(this, LowOnSpaceDialog.class);
			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			this.startActivity(mIntent);

			finish();
			return;
		}
		
	    setContentView(R.layout.fragment_layout);

	    
	    // setup Action Bar for tabs
	    actionBar = getActionBar();
	    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	    // remove the activity title to make space for tabs
	    actionBar.setDisplayShowTitleEnabled(false);
	    actionBar.setDisplayShowHomeEnabled(false);
	    
	    constructAlarmTabTitle();
	    constructTimerTabTitle();
	    constructWorldclockTabTitle();
	    constructStopwatchTabTitle();
	    

		intent = getIntent();
		if (intent != null) {
			if (intent.getAction() != null && intent.getAction().equals("LASTUSEDTAB")) {
				mCurrentTab = WORLDCLOCK_ID;
				intent = null;
			}
			else if (intent.getAction() != null && intent.getAction().equals("ALARMTAB")) {
				mCurrentTab = ALARM_ID;
				intent = null;
			}
			else if (intent.getAction() != null && intent.getAction().equals("TIMERTAB")) {
				mCurrentTab = TIMER_ID;
				intent = null;
			}
			else if (intent.getAction() != null && intent.getAction().equals("WORLDCLOCKTAB")) {
				mCurrentTab = WORLDCLOCK_ID;
				intent = null;
			}
			else if (intent.getAction() != null && intent.getAction().equals("STOPWATCHTAB")) {
				mCurrentTab = STOPWATCH_ID;
				intent = null;
			}			
			else {
				mCurrentTab = loadPreferences();
				intent = null;
			}
		}
		else {
			mCurrentTab = loadPreferences();	
		}
		
		Log.d(TAG, "currentTab = " + mCurrentTab);
	    actionBar.setSelectedNavigationItem(mCurrentTab);
	    savePreferences(mCurrentTab);
	    
		//sunghun.an@lge.com Common : Gesture Guide Pop up  [START]
		pref = getSharedPreferences("gesture_guide", 0);
		mGestureGuide = pref.getBoolean("gesture_guide",mGestureGuide);
		
		if(CommonUtil.getBuildOperator() == OPERATOR.VZW){
			
			/*If the first operation, the default is set*/
			setPreference(pref, "gesture_guide", true);
			
			if(mGestureGuide == false && CommonUtil.isFacingSensorSupported(this) && isGestureSetFlagInSetting() == false){
				showGestureGuide();
			}
		}else{
			if(mGestureGuide == false && CommonUtil.isFacingSensorSupported(this)){
				showGestureGuide();
			}
		} //End Of if
		
		
		//sunghun.an@lge.com Common : Gesture Guide Pop up  [END]
    }
	
	/**
	 * suein1209.kim
	 * == 1 (Gesture On)(None)
	 * == 0 (Gesture off)(Turn on / Dismiss)
	 * @return
	 */
	private boolean isGestureSetFlagInSetting(){
		int ret = Settings.System.getInt(getApplicationContext().getContentResolver(), "gesture_alarm", 1);
		return ret == 1;
	} //End Of Method isGestureSetFlagInSetting
	

	private void constructAlarmTabTitle() {
	    actionBar = getActionBar();

	    View view = getLayoutInflater().inflate(R.layout.tab_custom_view, null);
	    ImageView imageView = (ImageView)view.findViewById(R.id.tab_icon);
	    imageView.setImageResource(R.drawable.btn_alarm_tab);
	    TextView textView = (TextView)view.findViewById(R.id.tab_text);
	    textView.setText(R.string.sp_Alarms_Label_NORMAL);
	    
	    actionBar.addTab(actionBar.newTab().setCustomView(view)
	    		.setTag("alarmFragment")
	    		.setTabListener(new AlarmClockListener<AlarmFragment>(this,"alarmFragment",AlarmFragment.class)));
	}

	private void constructTimerTabTitle() {
	    actionBar = getActionBar();

	    View view = getLayoutInflater().inflate(R.layout.tab_custom_view, null);
	    ImageView imageView = (ImageView)view.findViewById(R.id.tab_icon);
	    imageView.setImageResource(R.drawable.btn_timer_tab);
	    TextView textView = (TextView)view.findViewById(R.id.tab_text);
	    textView.setText(R.string.superclock_timer);
	    
	    actionBar.addTab(actionBar.newTab().setCustomView(view)
	    		.setTag("timerFragment")
	    		.setTabListener(new AlarmClockListener<TimerFragment>(this,"timerFragment",TimerFragment.class)));
	}
	
	private void constructWorldclockTabTitle() {
	    actionBar = getActionBar();

	    View view = getLayoutInflater().inflate(R.layout.tab_custom_view, null);
	    ImageView imageView = (ImageView)view.findViewById(R.id.tab_icon);
	    imageView.setImageResource(R.drawable.btn_worldclock_tab);
	    TextView textView = (TextView)view.findViewById(R.id.tab_text);
	    textView.setText(R.string.sp_Worldclock_Label_ICS_NORMAL);
	    
	    actionBar.addTab(actionBar.newTab().setCustomView(view)
	    		.setTag("worldClockFragment")
	    		.setTabListener(new AlarmClockListener<WorldClockFragment>(this,"worldClockFragment",WorldClockFragment.class)));
	}
	
	private void constructStopwatchTabTitle() {
	    actionBar = getActionBar();

	    View view = getLayoutInflater().inflate(R.layout.tab_custom_view, null);
	    ImageView imageView = (ImageView)view.findViewById(R.id.tab_icon);
	    imageView.setImageResource(R.drawable.btn_stopwatch_tab);
	    TextView textView = (TextView)view.findViewById(R.id.tab_text);
	    textView.setText(R.string.sp_STOPWATCH_NORMAL);
	    
	    actionBar.addTab(actionBar.newTab().setCustomView(view)
	    		.setTag("stopWatchFragment")
	    		.setTabListener(new AlarmClockListener<StopWatchFragment>(this,"stopWatchFragment",StopWatchFragment.class)));
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
	} //End Of Method onDestroy
	
	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		setIntent(intent);
		
		intent = getIntent();
		if (intent != null) {
			if (intent.getAction() != null && intent.getAction().equals("LASTUSEDTAB")) {
				mCurrentTab = WORLDCLOCK_ID;
				intent = null;
			}
			else if (intent.getAction() != null && intent.getAction().equals("ALARMTAB")) {
				mCurrentTab = ALARM_ID;
				intent = null;
			}
			else if (intent.getAction() != null && intent.getAction().equals("TIMERTAB")) {
				mCurrentTab = TIMER_ID;
				intent = null;
			}
			else if (intent.getAction() != null && intent.getAction().equals("WORLDCLOCKTAB")) {
				mCurrentTab = WORLDCLOCK_ID;
				intent = null;
			}
			else if (intent.getAction() != null && intent.getAction().equals("STOPWATCHTAB")) {
				mCurrentTab = STOPWATCH_ID;
				intent = null;
			}			
			else {
				mCurrentTab = loadPreferences();
				intent = null;
			}
		}
		else {
			mCurrentTab = loadPreferences();	
		}
		
		Log.d(TAG, "currentTab = " + mCurrentTab);
	    actionBar.setSelectedNavigationItem(mCurrentTab);
	    savePreferences(mCurrentTab);		
	}
   
	/**
	 * Method loadPreferences.
	 * @return int
	 */
	protected int loadPreferences() {
		int mode = Context.MODE_PRIVATE;
		SharedPreferences sortbyPreferences = getSharedPreferences(LASTTABID,
				mode);

		return sortbyPreferences.getInt("currenttab", ALARM_ID);
	}

	/**
	 * Method savePreferences.
	 * @param currentTab int
	 */
	protected void savePreferences(int currentTab) {
		int mode = Context.MODE_PRIVATE;
		SharedPreferences sortbyPreferences = getSharedPreferences(LASTTABID,
				mode);
		SharedPreferences.Editor editor = sortbyPreferences.edit();
		this.mCurrentTab = currentTab;
		editor.putInt("currenttab", currentTab);
		this.mCurrentTab = currentTab;
		editor.commit();
	}
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
        Log.d(TAG, "onSaveInstanceState currentTab = " + mCurrentTab);
    }

    
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
		
		mCurrentTab = savedInstanceState.getInt("tab", 0);
		actionBar.setSelectedNavigationItem(mCurrentTab);
		savePreferences(mCurrentTab);
		Log.d(TAG, "onRestoreInstanceState currentTab = " + mCurrentTab);
	}


	private class AlarmClockListener<T extends Fragment> implements ActionBar.TabListener {
		private final Activity mActivity;
        private final String mTag;
        private final Class<T> mClass;
        private final Bundle mArgs;
        private Fragment mFragment;

        public AlarmClockListener(Activity activity, String tag, Class<T> clz) {
            this(activity, tag, clz, null);
        }

        public AlarmClockListener(Activity activity, String tag, Class<T> clz, Bundle args) {
            mActivity = activity;
            mTag = tag;
            mClass = clz;
            mArgs = args;

            // Check to see if we already have a fragment for this tab, probably
            // from a previously saved state.  If so, deactivate it, because our
            // initial state is that a tab isn't shown.
            mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
            if (mFragment != null && !mFragment.isDetached()) {
                FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
                ft.detach(mFragment);
                ft.commitAllowingStateLoss();
            }
        }

	    public void onTabSelected(Tab tab, FragmentTransaction ft) {
	    	hideKeyboard();
	    	
	    	if (mFragment == null) {
                mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
                ft.add(android.R.id.content, mFragment, mTag);
            } else {
                ft.attach(mFragment);
            }

	    	Log.d(TAG, "getActionBar().getSelectedNavigationIndex() = " + getActionBar().getSelectedNavigationIndex());
	    	
	    	
	    	/*[START]2012.02.15 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #134968*/
//			savePreferences(getActionBar().getSelectedNavigationIndex());
	    	/*[END]2012.02.15 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #134968*/
	    }

	    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
	    	if (mFragment != null) {
                ft.detach(mFragment);
            }
	    }

	    public void onTabReselected(Tab tab, FragmentTransaction ft) {
	        
	    }

	}
	/**
	 * Method onResume.
	 */
	@Override
	protected void onResume() {
		super.onResume();
		Log.i(TAG, "onResume");
		//[hyunjung78.park][1406] 2011.10.12 START
		if(isLowOnSpace){ 
			isLowOnSpace = false;
			return; 
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		/*[START]2012.02.15 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #134968*/
		savePreferences(getActionBar().getSelectedNavigationIndex());
		/*[START]2012.02.15 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #134968*/
	}

	
	  //sunghun.an@lge.com Common : Gesture Guide Pop up  [START]
  	private void showGestureGuide()
      {
  		LayoutInflater inflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
  		View layout = inflater.inflate(R.layout.popup_gesture_guide, null);
  		final ImageView mImageView = (ImageView) layout.findViewById(R.id.gestureImage);
  		mImageView.setImageDrawable(getResources().getDrawable(R.drawable.gesture_anim));
  		mAnimation = (AnimationDrawable) mImageView.getDrawable();
  		
  		TextView gtext = (TextView) layout.findViewById(R.id.gestureText);
  		gtext.setText(R.string.sp_gesture_info_alarm_NORMAL);

  		/*init check box*/
  		initCheckBoxInGesture(layout);
  		
  		Builder gestureGuideDlg = CommonUtil.getBuildOperator() == OPERATOR.VZW ? getAlarmVZWDialog() : getAlarmCommonDialog();
  		gestureGuideDlg.setView(layout).show();

  		new Handler().postDelayed(new Runnable()		 
  		{			  
  			@Override
  			public void run(){
  				if(mAnimation != null)
  				{
  					mAnimation.start(); 	
  				}
  			}	   
  		}, 1000); 
     	
      }

  	/**
  	 * suein1209.kim
  	 * init check box in gestuer pop-up
  	 */
  	private void initCheckBoxInGesture(View layout){
  		check= (CheckBox) layout.findViewById(R.id.GuideCheck);
  		
  		if(CommonUtil.getBuildOperator() == OPERATOR.VZW){
  			/*VZW model*/
  			
  			check.setVisibility(View.GONE);
  		}else{
  			/*Normal model*/
  			
  			check.setText(R.string.sp_do_not_show_this_again_NORMAL);
  			check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
  				
  				@Override
  				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
  					
  					/*[START] 2012.05.08 suein1209.kim OFFICIAL_EVENT.Mobile_12 - Defect #65747*/
  					check.playSoundEffect(SoundEffectConstants.CLICK);
  					/*[END] 2012.05.08 suein1209.kim OFFICIAL_EVENT.Mobile_12 - Defect #65747*/
  					
  					if(check.isChecked()){
  						CommonUtil.setGestureGuideChecked(true);
  					} else {
  						CommonUtil.setGestureGuideChecked(false);
  					}
  					
  				}
  			}); 
  			
  			if(CommonUtil.getGestureGuideChecked()){
  				check.setChecked(true);
  			} else {
  				check.setChecked(false);
  			}
  		}//End Of if
  		
  	} //End Of Method initCheckBoxInGesture
  	
  	/**
  	 * 2012.04.30 suein1209.kim
  	 * Set share preference
  	 */
  	private void setPreference(SharedPreferences spf, String key, boolean value){
		SharedPreferences.Editor edit = spf.edit();
		edit.putBoolean(key, value);
		edit.commit();
  	} //End Of Method setPreference
  	
  	/**
  	 * suein1209.kim
  	 * return Alarm VZW Dialog
  	 * @return
  	 */
  	private Builder getAlarmVZWDialog(){
  		
  		/*Gesture flag set*/
		mGestureGuide=true;
  		
  		Builder gestureGuideDlg = new AlertDialog.Builder(this)
		.setTitle(R.string.sp_gesture_guide_title_NORMAL)
				.setPositiveButton(R.string.sp_gestuer_TurnOn_NORMAL, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
					
				Settings.System.putInt(getContentResolver(), "gesture_alarm", 1);
			}
		})
		.setNegativeButton(R.string.dismiss, new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int which) {
				Log.e(TAG,"Gesture Setting");
			
				gestureDlgDismiss();
				
				/*[START] 2012.04.30 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #157447 */
				setPreference(pref, "gesture_guide", mGestureGuide);
				/*[END] 2012.04.30 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #157447 */

			}
		})
		.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
				gestureDlgDismiss();
				
				/*[START] 2012.04.30 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #157447 */
				setPreference(pref, "gesture_guide", mGestureGuide);
				/*[END] 2012.04.30 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #157447 */
            }
        })
        .setCancelable(false)
        .setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,	KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					dialog.dismiss();
				} //End of if
				
				return false;
			} //End Of onKey
		});
  		
  		return gestureGuideDlg;
  	} //End of Method getAlarmVZWDialog
  	
  	/**
  	 * suein1209.kim
  	 * return Alarm Common Dialog
  	 * @return
  	 */
  	private Builder getAlarmCommonDialog(){
  		Builder gestureGuideDlg = new AlertDialog.Builder(this)
  		.setTitle(R.string.sp_gesture_guide_title_NORMAL)
  		.setPositiveButton(R.string.timer_set_alerttone_ok, new DialogInterface.OnClickListener()
  		{
  			public void onClick(DialogInterface dialog, int which) {
  				
  				if(check.isChecked())
  				{
  					Log.e(TAG,"Check OK");
  					mGestureGuide=true;
  					
  					setPreference(pref, "gesture_guide", mGestureGuide);
  					
  				}
  				
  				gestureDlgDismiss();
  				
  			}
  		})
  		.setNegativeButton(R.string.sp_gesture_settings_NORMAL, new DialogInterface.OnClickListener() {
  			public void onClick(DialogInterface dialog, int which) {
  				Log.e(TAG,"Gesture Setting");

				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

				try {
					intent.setClassName("com.android.settings", "com.android.settings.Settings$GestureSettingsActivity");
					startActivity(intent);
				} catch (ActivityNotFoundException e) {
					Log.e(TAG, "Exception : AlarmFragment -> showGestureGuide : " + e.getMessage());
				} //End Of try

				gestureDlgDismiss();
  				
  			}
  		})
  		.setOnCancelListener(new DialogInterface.OnCancelListener() {
              @Override
              public void onCancel(DialogInterface dialog) {
  				gestureDlgDismiss();
              }
          });
  		
		return gestureGuideDlg;
  	} //End Of Method getAlarmCommonDialog

  	private void gestureDlgDismiss()
  	{
//  		((Activity)mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); 
  		if (mAnimation != null && mAnimation.isRunning()) {
  			mAnimation.stop();
  			mAnimation = null;
  		}	
  		if(gestureGuideDlg != null)
  		{
  			gestureGuideDlg.dismiss();
  			gestureGuideDlg=null;
  		}
  	}
  	//sunghun.an@lge.com Common : Gesture Guide Pop up  [END]
	
	public void hideKeyboard() {

		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// WBT TD2170347570
		if (imm != null) {
			if (imm.isActive()) {
				final View focusedView = getCurrentFocus();
				if (focusedView != null) {
					imm.hideSoftInputFromWindow(focusedView.getWindowToken(), 0);
					focusedView.clearFocus();
				}
			}
		}
	}
}
